import mysql.connector
from utils.common.logger import log
from configparser import ConfigParser
import os

db_config = {
    'user': 'common',
    'password': '123456',
    'host': '127.0.0.1',
    'database': 'poa_news',
    'raise_on_warnings': True
}


def readDBinfo(path):
    '''
    从conf.ini中读取数据库信息

    如果读取失败，则会使用默认信息(本地数据库)
    '''

    if os.path.exists(path) == False:
        log.logger.warning("无法打开数据库配置文件...")
        return None

    config = ConfigParser()
    config.read(path)
    return dict(config["mysql"])


class DBConnector:
    """
    数据库连接类，封装了mysql.connector

    Attributes:
        config，连接信息，默认为db_config
        connection，连接状态
    """

    def __init__(self, my_config: dict = db_config):
        if my_config is None:
            self.config = db_config
        else:
            self.config = my_config

        self.connection = None

    def __del__(self):
        if self.connection is not None:
            self.connection.close()

    def connect(self):
        """连接到数据库"""
        try:
            self.connection = mysql.connector.connect(**self.config)
            return True
        except Exception as e:
            log.logger.error(e)

        return False

    def query(self, sql: str):
        """
        根据sql语句查询结果

        返回值为：list[dict,dict...]，例如：[{row1},{row2},...]
        """

        if self.connection.is_connected() == False:
            log.logger.warning(
                "Database connection has not been established...")
            return None

        if "select" != sql[0:6].lower():
            log.logger.warning(
                "This Api is only for Select Query...")
            return None

        cursor = self.connection.cursor(dictionary=True)
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            return result
        except Exception as e:
            log.logger.error(e)

        return None

    def update(self, sql: str):
        """
        根据sql语句更新数据库，包括insert和update

        返回执行成功与否
        """

        if self.connection.is_connected() == False:
            log.logger.warning(
                "Database connection has not been established...")
            return False

        cursor = self.connection.cursor()
        try:
            cursor.execute(sql)
            self.connection.commit()
            return True
        except Exception as e:
            log.logger.error(e)

        return False
